#include "smarthome.h"
#include "ui_smarthome.h"
#include <QDebug>
#include <QJsonObject>
#include <QJsonArray>
#include <QSerialPortInfo>
#include <QTimer>
#include <QUdpSocket>
#include <QJsonDocument>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonArray>

smartHOme::smartHOme(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::smartHOme)
{
    ui->setupUi(this);

    // LCD 数字晶体管屏幕配置
    ui->lcdHum->setDecMode();  // 设置为十进制显示
    ui->lcdHum->setDigitCount(4); //设置可显示的位数
    ui->lcdHum->setSmallDecimalPoint(true);  // 小数点占位
    ui->lcdHum->setSegmentStyle(QLCDNumber::Flat);  //加粗
    ui->lcdHum->setStyleSheet("border:2pxsolidgreen;color:red;background:silver;");

    ui->lcdTemp->setDecMode();  // 设置为十进制显示
    ui->lcdTemp->setDigitCount(4); //设置可显示的位数
    ui->lcdTemp->setSmallDecimalPoint(true);  // 小数点占位
    ui->lcdTemp->setSegmentStyle(QLCDNumber::Flat);  //加粗
    ui->lcdTemp->setStyleSheet("border:2pxsolidgreen;color:red;background:silver;");

    ui->temp_now_lcd->setDecMode();  // 设置为十进制显示
    ui->temp_now_lcd->setDigitCount(4); //设置可显示的位数
    ui->temp_now_lcd->setSmallDecimalPoint(true);  // 小数点占位
    ui->temp_now_lcd->setSegmentStyle(QLCDNumber::Flat);  //加粗
    ui->temp_now_lcd->setStyleSheet("border:2pxsolidgreen;color:red;background:silver;");



    //时间晶体管设置

    QTimer *pTimer = new QTimer(this);

    ui->lcdTime->setDigitCount(19);
    ui->lcdTime->setSmallDecimalPoint(true);
    ui->lcdTime->setSegmentStyle(QLCDNumber::Flat);
    // 设置定时间隔

    pTimer->setInterval(1000);
    connect(pTimer, SIGNAL(timeout()), this, SLOT(onTimeOut()));

    // 启动定时器
    pTimer->start();


    pMqttClient=new QMqttClient(this);
    connect(pMqttClient,&QMqttClient::connected,
            this,&smartHOme::connected_isr); // 设置连接成功后回调函数
    connect(pMqttClient,&QMqttClient::messageReceived,
            this,&smartHOme::recv_message); // 设置接受消息回调函数



    /*
        MQTT客户端配置
    */
    pMqttClient->setHostname("1.15.226.213");
    pMqttClient->setPort(1883);
    pMqttClient->setClientId("SmartHome_gw_GEC6818");
    pMqttClient->setUsername("admin");
    pMqttClient->setPassword("lgh656898!");



    /*
        - 00 代表终端直连设备（NBIOT直连设备）
        - 01 代表网关设备
        - 10 代表服务端设备
        - 11 代表移动端设备
    */
    pMqttClient->connectToHost();



    foreach(QSerialPortInfo seriaoInfo,QSerialPortInfo::availablePorts());
    for(QSerialPortInfo &seriaoInfo:QSerialPortInfo::availablePorts())
    {
                   qDebug()<<seriaoInfo.portName();

               }
    qDebug( ) << "this is run";
    /*
     串口配置
    */


       pSerialPort=new QSerialPort(this);
       pSerialPort->setPortName("ttySAC3");

       pSerialPort->setBaudRate(QSerialPort::Baud115200); // 波特率115200
       pSerialPort->setParity(QSerialPort::NoParity); // 无奇偶校验位
       pSerialPort->setFlowControl(QSerialPort::NoFlowControl); // 无流控制
       pSerialPort->setStopBits(QSerialPort::OneStop); // 一位停止位
       pSerialPort->setDataBits(QSerialPort::Data8); // 8位数据位
       pSerialPort->open(QSerialPort::ReadWrite);// 读写模式打开


           connect(pSerialPort,&QSerialPort::readyRead,
                   this,&smartHOme::receive_data); // 设置接收回调



       //QNetworkAccessManager
       pNetworkAccessManager=new QNetworkAccessManager(this);
           connect(pNetworkAccessManager,
                   &QNetworkAccessManager::finished,
                   this,&smartHOme::request_Finished);

       // 图表设置

      // setupRealtimeDataDemo(customPlot);
       //setupDataDemo(customPlot);
      //customPlot->setFixedSize(360,350);

       for(int i=0; i<10; i++){
           tempnum[i] = 0;
       }
//      ui->mCustomPlot->setFixedSize(360,350);
//      ui->mCustomPlot->setFocusProxy(ui->mCustomPlot);

       QTimer *dataTimer= new QTimer();
       //connect(dataTimer,SIGNAL(timeout()),this,SLOT(showupdate()));
       connect(dataTimer,SIGNAL(timeout()),this,SLOT(SimpleDemo()));
       dataTimer->start(5000);


}

smartHOme::~smartHOme()
{
    delete ui;
}


/*
    更新时间晶体管
*/
void smartHOme::onTimeOut()
{
    /**
    QString url = "http://tf.nist.gov/tf-cgi/servers.cgi";
    QTcpSocket *socket = new QTcpSocket();
    socket->connectToHost(url, 13);
    if (socket->waitForConnected())
    {
        if (socket->waitForReadyRead())
        {
            QString str(socket->readAll());
            str = str.trimmed();
            QStringList strList = str.split(" ");
            //qDebug() << strList;
            qDebug() << str;
        }
    }
    socket->close();
    delete socket;
    **/


    // 获取系统当前时间
       QDateTime dateTime = QDateTime::fromTime_t(getWebTime());
       // 显示的内容
       ui->lcdTime->display(dateTime.toString("yyyy-MM-dd HH:mm:ss.zzz"));
}


/*
    MQTT连接成功后执行
*/
void smartHOme::connected_isr()
{
    qDebug()<<"Connected successfully!";
    pMqttClient->subscribe(QMqttTopicFilter(QString("smartHome_ByZX/10")));
    pMqttClient->subscribe(QMqttTopicFilter(QString("smartHome_ByZX/11")));
}

/*
    当接收到MQTT消息时处理回调
*/
void smartHOme::recv_message(QByteArray message){
    if(message=="01" && ui->lightButton->text() == "开灯")
    {
        on_lightButton_clicked();
    }else if(message=="00" && ui->lightButton->text() == "关灯")
    {
        on_lightButton_clicked();
    }else if(message=="11" && ui->fanButton_2->text() == "开风扇")
    {
        on_fanButton_2_clicked();
    }else if(message=="10" && ui->fanButton_2->text() == "关风扇")
    {
        on_fanButton_2_clicked();
    }


}

/*
    接受到串口消息时槽函数
*/
void smartHOme::receive_data(){
        //qDebug() << "有消息！";
        QByteArray buff;
        buff=pSerialPort->readAll();
        QString buf(buff);
        QStringList dataList = buf.split("/");

        ui->lcdTemp->display(dataList[0]);
        ui->lcdHum->display(dataList[1]);

        QJsonObject *temp = new QJsonObject();
        QJsonObject *hum = new QJsonObject();
        QJsonObject *led = new QJsonObject();
        QJsonObject *fan = new QJsonObject();
//        {"id":"temp",
//             "device":"efbb1c28-d295-11eb-bb43-f4b5202c9ef6",
//             "dataType":"data",
//             "value":24
//            },
//        7644ad57-d91f-6786-9745-93f1f7e1245c
//        73473812-4c83-820e-8720-04e4abda0133
//        735142bd-1017-ad1c-9608-609e39fcb16b
//        30f3f8f7-9c93-3d76-b79a-1589958540d0
        temp->insert("id","temp");
        temp->insert("device","7644ad57-d91f-6786-9745-93f1f7e1245c");
        temp->insert("dataType","data");
        temp->insert("value",dataList[0]);

        hum->insert("id","hum");
        hum->insert("device","7644ad57-d91f-6786-9745-93f1f7e1245c");
        hum->insert("dataType","data");
        hum->insert("value",dataList[1]);

        led->insert("id","led");
        led->insert("device","735142bd-1017-ad1c-9608-609e39fcb16b");
        led->insert("dataType","state");
        led->insert("value",dataList[2]);

        fan->insert("id","fan");
        fan->insert("device","30f3f8f7-9c93-3d76-b79a-1589958540d0");
        fan->insert("dataType","state");
        fan->insert("value",dataList[3]);

          QJsonArray list;
        //qDebug() << QString(QJsonDocument(*hum).toJson());
          list.append(*temp);
          list.append(*led);
          list.append(*hum);
          list.append(*fan);

        //qDebug() << QString(QJsonDocument(list).toJson()).toLocal8Bit();
          //qDebug() << QString("[{value:\"33\"}]").toLocal8Bit();
        //pMqttClient->publish(QMqttTopicName("smartHome_ByZX/01"),QString("[{value:\"33\"}]").toLocal8Bit());
        pMqttClient->publish(QMqttTopicName("smartHome_ByZX/01"),QString(QJsonDocument(list).toJson()).toLocal8Bit());  // 推送消息

         }

/*
    点击开灯按钮时处理的槽函数
*/
void smartHOme::on_lightButton_clicked()
{
    QString cmdStr;
    if(ui->lightButton->text()=="开灯")
    {
         cmdStr= "01";
         ui->lightButton->setText("关灯");
    }else if(ui->lightButton->text()=="关灯")
    {
        cmdStr = "00";
        ui->lightButton->setText("开灯");
    }

    //cmdStr=cmdStr;//去掉前后的空白字符
    //qDebug() << cmdStr.length();
    pSerialPort->write(cmdStr.toLocal8Bit());

}

/*
    点击开风扇处理的槽函数
*/
void smartHOme::on_fanButton_2_clicked()
{
        QString cmdStr;
        if(ui->fanButton_2->text()=="开风扇")
        {
             cmdStr= "11";
             ui->fanButton_2->setText("关风扇");
        }else if(ui->fanButton_2->text()=="关风扇")
        {
            cmdStr = "10";
            ui->fanButton_2->setText("开风扇");
        }

        //cmdStr=cmdStr.trimmed();//去掉前后的空白字符

        pSerialPort->write(cmdStr.toLocal8Bit());
}

void smartHOme::change_chart()
{
    //动态分配空间

}

void smartHOme::SimpleDemo()
{
    QNetworkRequest request;
   request.setUrl(QUrl("http://1.15.226.213:8000/weatherby24hours"));

    pNetworkAccessManager->get(request);

}
void smartHOme::request_Finished(QNetworkReply *reply){
    if(reply->error()!=QNetworkReply::NoError)
        {
            qDebug()<<"error:"<<reply->errorString();
            return;
        }
        buf=reply->readAll();
        start += 30;
        QJsonDocument document = QJsonDocument::fromJson(buf);
        //qDebug() << document.array().at(1).toObject().find("value").value().toString().toDouble();

        for (int i=0;i<23;i++) {
                times[i]=document.array().at(i).toObject().find("time").value().toString().toDouble();
               tempnum[i]=document.array().at(i).toObject().find("temp").value().toString().toDouble();
        };
        ui->temp_now_lcd->display(document.array().at(1).toObject().find("temp").value().toString()+"C");

        SimpleDemo(ui->mCustomPlot,tempnum,23);

}

void smartHOme::SimpleDemo(QCustomPlot *customPlot,double tempnum[23],double n)
{

    QVector <double> temp(3600);
    QVector <double> time(3600);



    for (int i = 0 ;i<n ;i++ ) {
        temp[i] = tempnum[i];

    }
    for (int i = 0 ;i<n ;i++ ) {
        time[i] = times[i];

    }



    customPlot->addGraph();
    customPlot->graph(0)->setPen(QPen(QColor(70,0,70)));
    customPlot->graph(0)->setData(time,temp);

    customPlot->xAxis->setLabel("time/h");
    customPlot->yAxis->setLabel("温度/℃");
    customPlot->xAxis->setRange(1,23);
    customPlot->xAxis->setSubTickLength(1);
    customPlot->yAxis->setRange(-15,45);

    customPlot->replot();
}

qint32 smartHOme::getWebTime(){
        QUdpSocket udpSocket;
        udpSocket.connectToHost("time.windows.com", 123);
        if(udpSocket.waitForConnected(3000)){
            qint8 LI=0;
            qint8 VN=3;
            qint8 MODE=3;
            qint8 STRATUM=0;
            qint8 POLL=4;
            qint8 PREC=-6;
            QDateTime epoch(QDate(1900,1,1));
            qint32 second=quint32(epoch.secsTo(QDateTime::currentDateTime()));
            qint32 temp=0;
            QByteArray timeRequest(48, 0);
            timeRequest[0]=(LI <<6) | (VN <<3) | (MODE);
            timeRequest[1]=STRATUM;
            timeRequest[2]=POLL;
            timeRequest[3]=PREC & 0xff;
            timeRequest[5]=1;
            timeRequest[9]=1;
            timeRequest[40]=(temp=(second&0xff000000)>>24);
            temp=0;
            timeRequest[41]=(temp=(second&0x00ff0000)>>16);
            temp=0;
            timeRequest[42]=(temp=(second&0x0000ff00)>>8);
            temp=0;
            timeRequest[43]=((second&0x000000ff));
            udpSocket.flush();
            udpSocket.write(timeRequest);
            udpSocket.flush();
            if(udpSocket.waitForReadyRead(3000)){
                QByteArray newTime;
                QDateTime epoch(QDate(1900, 1, 1));
                QDateTime unixStart(QDate(1970, 1, 1));
                do
                {
                    newTime.resize(udpSocket.pendingDatagramSize());
                    udpSocket.read(newTime.data(), newTime.size());
                }while(udpSocket.hasPendingDatagrams());
                QByteArray TransmitTimeStamp ;
                TransmitTimeStamp=newTime.right(8);
                quint32 seconds=TransmitTimeStamp[0];
                quint8 temp=0;
                for(int j=1;j<=3;j++)
                {
                    seconds=seconds<<8;
                    temp=TransmitTimeStamp[j];
                    seconds=seconds+temp;
                }
                quint32 t = seconds-epoch.secsTo(unixStart) + 28800;
                //qDebug() << __FUNCTION__ << "song" << t;
                return t;
    //            time.setTime_t(seconds-epoch.secsTo(unixStart));
            }
        }

        return -1;

}





